/**
 * Created by rongyao on 2017/10/18.
 */
/**
 * Created by rongyao on 2017/10/17.
 */
var mongoose = require('mongoose');
const News = require('../models/news.model');
const Comment = require('../models/comment.model');
const async = require('async');

exports.create = function (req, res, next) {
	var news = new News(req.body);
	news.save().then(data => {
		res.json(data);
	});
}

exports.get = function (req, res, next) {
	var id = req.params.id;
	News.findById(id, function (err, data) {
		res.json(data);
	})
}

exports.update = function (req, res, next) {
	var id = req.params.id;
	News.findByIdAndUpdate(id, {$set: req.body}, {new: false})
		.then(data => {
			res.json(data);
		})
}

exports.remove = function (req, res, next) {
	var id = req.params.id;
	News.findByIdAndRemove(id, function (data) {
		res.json(data);
	})
}

exports.list = function (req, res, next) {
	console.log(req.body.page);
	var page = req.body.page ? req.body.page : 1;
	var limit = req.body.rows ? req.body.rows : 10;
	var queryCondition = {};
	if (req.body.keyWords && req.body.keyWords.trim().length > 0) {
		title = req.body.keyWords;
		queryCondition = {
			"title": new RegExp(title, 'i'),
		}
	}
	if (req.body.cateId && req.body.cateId.length > 0) {
		queryCondition.cateId = req.body.cateId;
	}
	
	if (req.body.ids && req.body.ids.length > 0) {
		
		queryCondition.cateId = {$in: req.body.ids};
	}
	News.paginate(queryCondition, {page: page - 0, limit: limit - 0, sort: {date: -1}}, function (err, result) {
		async.map(result.docs,function (news,callback) {
			Comment.count({cateId:news._id},function (err,count) {
				if(err){
					return;
				}else{
					news.commentCount = count;
					callback();
				}
			})
		},function (err) {
			result.rows = result.docs;
			delete result.docs;
			res.json(result);
		})
		
		
		// console.log(result);
		// res.json(result);
	});
}

exports.deletes = function (req, res, next) {
	var ids = req.body.ids;
	console.log(ids);
	console.log(ids.split(','));
	if(ids.split(',').length>0){
		News.remove({_id: {$in: ids.split(',')}}).then(data=>{
			res.json({'msg':"删除成功"})
		})
	}
}
